from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.admin.views.decorators import staff_member_required

from models import DisplayNameOption, EnableOption, BooleanOption, ChoiceOption, FloatOption, IntOption, TextOption
from models import EnableOptionForm, BooleanOptionForm, ChoiceOptionForm, FloatOptionForm, IntOptionForm, TextOptionForm

# Create your views here.
def GenerateOptionFormset(postinfo=None):
    Forms = []
    for item in EnableOption.objects.all():
        Forms.append(EnableOptionForm(postinfo,instance=item,prefix="enable-%d"%item.id))
    for item in BooleanOption.objects.all():
        Forms.append(BooleanOptionForm(postinfo,instance=item,prefix="bool-%d"%item.id))
    for item in ChoiceOption.objects.all():
        Forms.append(ChoiceOptionForm(postinfo,instance=item,prefix="choice-%d"%item.id))
    for item in FloatOption.objects.all():
        Forms.append(FloatOptionForm(postinfo,instance=item,prefix="float-%d"%item.id))
    for item in IntOption.objects.all():
        Forms.append(IntOptionForm(postinfo,instance=item,prefix="int-%d"%item.id))
    for item in TextOption.objects.all():
        Forms.append(TextOptionForm(postinfo,instance=item,prefix="text-%d"%item.id))
    Forms.sort(key=lambda form: "%s.%s" %(form.instance.app,form.instance.name))
    return Forms
    
@staff_member_required
def option_display(request):
    if request.method == "POST":
        forms = GenerateOptionFormset(request.POST)
        for form in forms:
            if form.is_valid():
                if form.has_changed():
                    form.save()
    forms = GenerateOptionFormset()
    
    
    return render_to_response('admin/option_display.html',{'forms':forms, 'title':'Options','app_label':'Options'},context_instance=RequestContext(request))